package com.hjq.mallproduct.service.impl;

import com.hjq.common.constants.ProductConstants;
import com.hjq.mallproduct.dao.AttrGroupDao;
import com.hjq.mallproduct.dao.CategoryDao;
import com.hjq.mallproduct.entity.AttrAttrgroupRelationEntity;
import com.hjq.mallproduct.entity.AttrGroupEntity;
import com.hjq.mallproduct.entity.CategoryEntity;
import com.hjq.mallproduct.entity.vo.AttrResponseVO;
import com.hjq.mallproduct.entity.vo.AttrVO;
import com.hjq.mallproduct.service.AttrAttrgroupRelationService;
import com.hjq.mallproduct.service.CategoryService;
import com.mysql.cj.util.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hjq.common.utils.PageUtils;
import com.hjq.common.utils.Query;

import com.hjq.mallproduct.dao.AttrDao;
import com.hjq.mallproduct.entity.AttrEntity;
import com.hjq.mallproduct.service.AttrService;
import org.springframework.transaction.annotation.Transactional;

@Transactional
@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {
    @Autowired
    private AttrAttrgroupRelationService aaRelationEntityService;
    //private AttrAttrgroupRelationDao aaRelationEntityService;
    @Autowired
    private CategoryDao categoryDao;
    @Autowired
    private AttrGroupDao attrDao;
    @Autowired
    private CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void saveAttrByVO(AttrVO attr) {
        Long attrGroupId = attr.getAttrGroupId();
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        this.save(attrEntity);
        Long attrId = attrEntity.getAttrId();
        //System.out.println(attrId);
        if((attrGroupId != null && Objects.equals(ProductConstants.AttrEnum.ATTR_BASE.code,attrEntity.getAttrType()))){
            aaRelationEntityService.saveByAttrIdAndGroupId(attrId,attrGroupId);
        }

    }

    @Override
    public PageUtils queryBasePage(Map<String, Object> params, Long categoryId, String type) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        String key = (String)params.get("key");
        boolean hasKey=false;
        boolean hasCatId=false;
        if(!StringUtils.isEmptyOrWhitespaceOnly(key)){
            wrapper.eq("attr_id",key).or().like("attr_name",key).or().like("value_select",key);
            hasKey=true;
        }

        if(categoryId!=0){
            if(hasKey){
                wrapper.and((wrapper1)->{
                    wrapper1.eq("catelog_id",categoryId);
                });
            }
            else {
                wrapper.eq("catelog_id",categoryId);
            }
            hasCatId=true;

        }
//        if("sale".equals(type)){
//            if(!hasKey&&!hasCatId){
//                wrapper.eq("attr_type",0);
//            }
//            else{
//                wrapper.and((wrapper1)->{
//                    wrapper1.eq("attr_type",0);
//                });
//            }
//        }

        if(!hasKey&&!hasCatId){
                wrapper.eq("attr_type","base".equalsIgnoreCase(type)?ProductConstants.AttrEnum.ATTR_BASE.code:ProductConstants.AttrEnum.ATTR_SALE.code);
            }
            else{
                wrapper.and((wrapper1)->{
                    wrapper1.eq("attr_type","base".equalsIgnoreCase(type)?ProductConstants.AttrEnum.ATTR_BASE.code:ProductConstants.AttrEnum.ATTR_SALE.code);
                });
            }

        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );
        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> pageRecords = page.getRecords();

        List<AttrResponseVO> responseVOS = pageRecords.stream().map((item) -> {
            AttrResponseVO attrResponseVO = new AttrResponseVO();
            //先复制原属性
            BeanUtils.copyProperties(item, attrResponseVO);

            //查询两个名字属性
            Long attrId = attrResponseVO.getAttrId();
            //查询Attr和AttrGroup的关系表得到attrGroupId
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = aaRelationEntityService.getOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            //查询AttrGroup,得到名字
            if (attrAttrgroupRelationEntity!= null) {
                Long attrGroupId = attrAttrgroupRelationEntity.getAttrGroupId();
                AttrGroupEntity attrGroupEntity = attrDao.selectById(attrGroupId);
                attrResponseVO.setAttrGroupName(attrGroupEntity.getAttrGroupName());
            }
            //查询CategoryName
            CategoryEntity categoryEntity=null;
            if(categoryId!=0){
                categoryEntity = categoryDao.selectById(categoryId);
            }else {
                Long catelogId = item.getCatelogId();
                categoryEntity = categoryDao.selectById(catelogId);
            }

            if (categoryEntity != null) {
                attrResponseVO.setCategoryName(categoryEntity.getName());
            }
            return attrResponseVO;
        }).collect(Collectors.toList());
        pageUtils.setList(responseVOS);

        return pageUtils ;


    }
    @Transactional
    @Cacheable(value = "attr",key = "'attrinfo:'+#root.args[0]")
    @Override
    public AttrResponseVO getAttrInfoWithCatWholePath(Long attrId) {
        //先把现有属性获得
        AttrEntity attrEntity = this.getById(attrId);
        AttrResponseVO attrResponseVO = new AttrResponseVO();
        BeanUtils.copyProperties(attrEntity,attrResponseVO);
        //查询两个名字属性
        //Long attrId = attrResponseVO.getAttrId();
        //查询Attr和AttrGroup的关系表得到attrGroupId
        AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = aaRelationEntityService.getOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
        //查询AttrGroup,得到名字
        if (attrAttrgroupRelationEntity!= null) {
            Long attrGroupId = attrAttrgroupRelationEntity.getAttrGroupId();
            AttrGroupEntity attrGroupEntity = attrDao.selectById(attrGroupId);
            attrResponseVO.setAttrGroupName(attrGroupEntity.getAttrGroupName());
            attrResponseVO.setAttrGroupId(attrGroupEntity.getAttrGroupId());
        }
        //查询categoryName和Category全路径
        Long catelogId = attrResponseVO.getCatelogId();
        String catName = categoryDao.selectById(catelogId).getName();
        attrResponseVO.setCategoryName(catName);
        List<Long> categoryPathList = categoryService.getCategoryPath(catelogId);
        Long[] categoryPath = categoryPathList.toArray(new Long[categoryPathList.size()]);
        attrResponseVO.setCatelogPath(categoryPath);


        return attrResponseVO;
    }

    @Override
    public void updateAttrByVO(AttrVO attr) {
        Long attrGroupId = attr.getAttrGroupId();
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        this.updateById(attrEntity);
        Long attrId = attrEntity.getAttrId();
        //System.out.println(attrId);
        //有可能之前没设置，后来设置
        AttrAttrgroupRelationEntity aaRelationEntity = aaRelationEntityService.getOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));

        if(aaRelationEntity==null){
            aaRelationEntityService.saveByAttrIdAndGroupId(attrId,attrGroupId);
        }
        if(attrGroupId !=null && Objects.equals(ProductConstants.AttrEnum.ATTR_BASE.code,attrEntity.getAttrType())){
            aaRelationEntityService.updateByAttrIdAndGroupId(attrId,attrGroupId);
        }


    }



}